<template>
  <div class="settings-page">
    <h2>桌面应用设置</h2>
    
    <div class="settings-section">
      <n-form
        ref="formRef"
        :model="electronSettings"
        label-placement="left"
        label-width="160"
        require-mark-placement="right-hanging"
      >
        <!-- 窗口设置 -->
        <n-divider>窗口设置</n-divider>
        
        <n-form-item label="启动时最大化" path="startMaximized">
          <n-switch v-model:value="electronSettings.startMaximized" />
        </n-form-item>
        
        <n-form-item label="记住窗口位置和大小" path="rememberWindowState">
          <n-switch v-model:value="electronSettings.rememberWindowState" />
        </n-form-item>
        
        <n-form-item label="始终置顶" path="alwaysOnTop">
          <n-switch v-model:value="electronSettings.alwaysOnTop" />
        </n-form-item>
        
        <n-form-item label="多窗口模式" path="multiWindowMode">
          <n-switch v-model:value="electronSettings.multiWindowMode" />
        </n-form-item>
        
        <n-form-item label="窗口主题" path="windowTheme">
          <n-radio-group v-model:value="electronSettings.windowTheme">
            <n-space>
              <n-radio value="system">跟随系统</n-radio>
              <n-radio value="light">浅色</n-radio>
              <n-radio value="dark">深色</n-radio>
            </n-space>
          </n-radio-group>
        </n-form-item>
        
        <!-- 系统集成 -->
        <n-divider>系统集成</n-divider>
        
        <n-form-item label="开机自启动" path="autoStart">
          <n-switch v-model:value="electronSettings.autoStart" />
        </n-form-item>
        
        <n-form-item label="关联文件类型" path="fileAssociations">
          <n-space vertical align="start">
            <n-checkbox v-model:checked="electronSettings.associateSPF">皮影快闪项目文件 (.spf)</n-checkbox>
            <n-checkbox v-model:checked="electronSettings.associateSPC">皮影快闪角色文件 (.spc)</n-checkbox>
            <n-checkbox v-model:checked="electronSettings.associateSPS">皮影快闪场景文件 (.sps)</n-checkbox>
          </n-space>
        </n-form-item>
        
        <n-form-item label="系统托盘" path="systemTray">
          <n-space vertical align="start">
            <n-checkbox v-model:checked="electronSettings.enableTray">启用系统托盘图标</n-checkbox>
            <n-checkbox v-model:checked="electronSettings.minimizeToTray" :disabled="!electronSettings.enableTray">
              最小化到托盘
            </n-checkbox>
            <n-checkbox v-model:checked="electronSettings.closeToTray" :disabled="!electronSettings.enableTray">
              关闭时最小化到托盘
            </n-checkbox>
          </n-space>
        </n-form-item>
        
        <!-- 更新设置 -->
        <n-divider>更新设置</n-divider>
        
        <n-form-item label="自动检查更新" path="autoCheckUpdates">
          <n-switch v-model:value="electronSettings.autoCheckUpdates" />
        </n-form-item>
        
        <n-form-item label="更新频率" path="updateCheckFrequency" v-if="electronSettings.autoCheckUpdates">
          <n-select
            v-model:value="electronSettings.updateCheckFrequency"
            :options="updateFrequencyOptions"
            style="width: 200px"
          />
        </n-form-item>
        
        <n-form-item label="更新通道" path="updateChannel">
          <n-select
            v-model:value="electronSettings.updateChannel"
            :options="updateChannelOptions"
            style="width: 200px"
          />
        </n-form-item>
        
        <n-form-item label="自动下载更新" path="autoDownloadUpdates" v-if="electronSettings.autoCheckUpdates">
          <n-switch v-model:value="electronSettings.autoDownloadUpdates" />
        </n-form-item>
        
        <n-form-item label="当前版本">
          <n-space align="center">
            <n-tag type="info">v{{ appVersion }}</n-tag>
            <n-button quaternary size="small" @click="checkForUpdates" :loading="checkingUpdates">
              检查更新
            </n-button>
          </n-space>
        </n-form-item>
        
        <!-- 高级设置 -->
        <n-divider>高级设置</n-divider>
        
        <n-form-item label="开发者工具" path="devTools">
          <n-switch v-model:value="electronSettings.devTools" />
        </n-form-item>
        
        <n-form-item label="硬件加速" path="hardwareAcceleration">
          <n-switch v-model:value="electronSettings.hardwareAcceleration" />
        </n-form-item>
        
        <n-form-item label="进程优先级" path="processPriority">
          <n-select
            v-model:value="electronSettings.processPriority"
            :options="processPriorityOptions"
            style="width: 200px"
          />
        </n-form-item>
        
        <n-form-item label="日志级别" path="logLevel">
          <n-select
            v-model:value="electronSettings.logLevel"
            :options="logLevelOptions"
            style="width: 200px"
          />
        </n-form-item>
        
        <n-form-item label="日志文件">
          <n-space>
            <n-button @click="openLogDirectory">
              <template #icon><n-icon><FolderOpenOutline /></n-icon></template>
              打开日志目录
            </n-button>
            <n-button @click="exportLogs">
              <template #icon><n-icon><DownloadOutline /></n-icon></template>
              导出日志
            </n-button>
          </n-space>
        </n-form-item>
        
        <n-form-item label="缓存管理">
          <n-space>
            <n-button @click="clearAppCache">
              <template #icon><n-icon><TrashOutline /></n-icon></template>
              清理应用缓存
            </n-button>
            <n-button @click="resetAppSettings" type="warning">
              <template #icon><n-icon><RefreshOutline /></n-icon></template>
              重置所有设置
            </n-button>
          </n-space>
        </n-form-item>
      </n-form>
      
      <div class="form-actions">
        <n-space>
          <n-button @click="resetToDefaults" quaternary>恢复默认设置</n-button>
          <n-button type="primary" @click="saveSettings">保存设置</n-button>
        </n-space>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useMessage, useDialog } from 'naive-ui'
import {
  NForm,
  NFormItem,
  NSwitch,
  NSelect,
  NCheckbox,
  NRadioGroup,
  NRadio,
  NButton,
  NSpace,
  NDivider,
  NTag,
  NIcon
} from 'naive-ui'
import {
  FolderOpenOutline,
  DownloadOutline,
  TrashOutline,
  RefreshOutline
} from '@vicons/ionicons5'

const message = useMessage()
const dialog = useDialog()
const formRef = ref(null)

// 应用版本
const appVersion = ref('1.0.0')
const checkingUpdates = ref(false)

// Electron设置表单
const electronSettings = reactive({
  // 窗口设置
  startMaximized: false,
  rememberWindowState: true,
  alwaysOnTop: false,
  multiWindowMode: false,
  windowTheme: 'system',
  
  // 系统集成
  autoStart: false,
  associateSPF: true,
  associateSPC: true,
  associateSPS: true,
  enableTray: true,
  minimizeToTray: false,
  closeToTray: true,
  
  // 更新设置
  autoCheckUpdates: true,
  updateCheckFrequency: 'daily',
  updateChannel: 'stable',
  autoDownloadUpdates: true,
  
  // 高级设置
  devTools: false,
  hardwareAcceleration: true,
  processPriority: 'normal',
  logLevel: 'info'
})

// 更新频率选项
const updateFrequencyOptions = [
  { label: '每次启动时', value: 'startup' },
  { label: '每天', value: 'daily' },
  { label: '每周', value: 'weekly' },
  { label: '每月', value: 'monthly' }
]

// 更新通道选项
const updateChannelOptions = [
  { label: '稳定版', value: 'stable' },
  { label: '测试版', value: 'beta' },
  { label: '开发版', value: 'dev' }
]

// 进程优先级选项
const processPriorityOptions = [
  { label: '低', value: 'low' },
  { label: '正常', value: 'normal' },
  { label: '高', value: 'high' },
  { label: '非常高', value: 'very-high' }
]

// 日志级别选项
const logLevelOptions = [
  { label: '错误', value: 'error' },
  { label: '警告', value: 'warn' },
  { label: '信息', value: 'info' },
  { label: '调试', value: 'debug' },
  { label: '详细', value: 'verbose' }
]

// 默认设置
const defaultSettings = {
  // 窗口设置
  startMaximized: false,
  rememberWindowState: true,
  alwaysOnTop: false,
  multiWindowMode: false,
  windowTheme: 'system',
  
  // 系统集成
  autoStart: false,
  associateSPF: true,
  associateSPC: true,
  associateSPS: true,
  enableTray: true,
  minimizeToTray: false,
  closeToTray: true,
  
  // 更新设置
  autoCheckUpdates: true,
  updateCheckFrequency: 'daily',
  updateChannel: 'stable',
  autoDownloadUpdates: true,
  
  // 高级设置
  devTools: false,
  hardwareAcceleration: true,
  processPriority: 'normal',
  logLevel: 'info'
}

// 检查更新
function checkForUpdates() {
  checkingUpdates.value = true
  message.info('正在检查更新...')
  
  // 模拟检查更新过程
  setTimeout(() => {
    const hasUpdate = Math.random() > 0.7
    
    if (hasUpdate) {
      dialog.info({
        title: '发现新版本',
        content: '发现新版本 v1.1.0，是否立即更新？',
        positiveText: '立即更新',
        negativeText: '稍后提醒',
        onPositiveClick: () => {
          message.success('开始下载更新')
          // 实际项目中，这里会调用Electron的自动更新API
        }
      })
    } else {
      message.success('您使用的已经是最新版本')
    }
    
    checkingUpdates.value = false
  }, 2000)
}

// 打开日志目录
function openLogDirectory() {
  message.info('正在打开日志目录...')
  // 实际项目中，这里会调用Electron的shell.openPath API
}

// 导出日志
function exportLogs() {
  message.info('正在导出日志...')
  // 实际项目中，这里会调用Electron的dialog.showSaveDialog API
  
  setTimeout(() => {
    message.success('日志已导出')
  }, 1000)
}

// 清理应用缓存
function clearAppCache() {
  dialog.warning({
    title: '清理缓存',
    content: '确定要清理应用缓存吗？这将清除所有临时文件，但不会影响您的项目和设置。',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => {
      message.info('正在清理缓存...')
      
      // 模拟清理过程
      setTimeout(() => {
        message.success('缓存已清理')
      }, 1500)
    }
  })
}

// 重置应用设置
function resetAppSettings() {
  dialog.warning({
    title: '重置所有设置',
    content: '确定要重置所有应用设置吗？这将恢复所有设置到默认状态，但不会删除您的项目和素材。',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => {
      message.info('正在重置设置...')
      
      // 模拟重置过程
      setTimeout(() => {
        message.success('所有设置已重置')
        resetToDefaults()
      }, 1500)
    }
  })
}

// 加载设置
function loadSettings() {
  // 实际项目中，这里会从Electron的存储API加载设置
  const savedSettings = localStorage.getItem('electronSettings')
  if (savedSettings) {
    try {
      const parsedSettings = JSON.parse(savedSettings)
      Object.assign(electronSettings, parsedSettings)
    } catch (error) {
      console.error('Failed to parse saved settings:', error)
    }
  }
  
  // 获取应用版本
  // 实际项目中，这里会从Electron的app.getVersion() API获取
  appVersion.value = '1.0.0'
}

// 保存设置
function saveSettings() {
  // 实际项目中，这里会调用Electron的存储API保存设置
  localStorage.setItem('electronSettings', JSON.stringify(electronSettings))
  message.success('设置已保存')
  
  // 应用设置
  applySettings()
}

// 应用设置
function applySettings() {
  // 实际项目中，这里会调用Electron的API应用设置
  console.log('Electron settings applied:', electronSettings)
  
  // 例如，设置窗口总是置顶
  // if (electronSettings.alwaysOnTop) {
  //   window.electron.setAlwaysOnTop(true)
  // }
}

// 恢复默认设置
function resetToDefaults() {
  Object.assign(electronSettings, defaultSettings)
  message.info('已恢复默认设置')
}

// 组件挂载时加载设置
onMounted(() => {
  loadSettings()
})
</script>

<style lang="scss" scoped>
.settings-page {
  padding: 0 16px;
  
  h2 {
    margin-top: 0;
    margin-bottom: 24px;
    font-weight: 500;
  }
  
  .settings-section {
    max-width: 800px;
  }
  
  .form-actions {
    margin-top: 32px;
    display: flex;
    justify-content: flex-end;
  }
}
</style> 